package com.a3dweijing.wetouch2.fragment;

import static android.app.Activity.RESULT_OK;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.a3dweijing.wetouch2.Activity.BuyVipActivity.BUYVIPACTIVITYCODE;
import static com.a3dweijing.wetouch2.Util.FileUtil.CACHE_DIR;
import static com.a3dweijing.wetouch2.Util.FileUtil.shearshead;
import static com.a3dweijing.wetouch2.bean.EvenMsg.RESETNICKNAMEACTIVITYRESTNAME;
import static com.a3dweijing.wetouch2.bean.EvenMsg.WXPAYFAIL;
import static com.a3dweijing.wetouch2.bean.EvenMsg.WXPAYSUCCESS;
import static com.a3dweijing.wetouch2.wxapi.WXPayEntryActivity.BUYVIP;

import java.io.File;
import java.util.ArrayList;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Activity.ApplyForExpertsActivitiy;
import com.a3dweijing.wetouch2.Activity.BuyVipActivity;
import com.a3dweijing.wetouch2.Activity.EvaluatedListActivity;
import com.a3dweijing.wetouch2.Activity.HealthInquiriesActivity;
import com.a3dweijing.wetouch2.Activity.MyPriviteActivity;
import com.a3dweijing.wetouch2.Activity.MyWalletActivity;
import com.a3dweijing.wetouch2.Activity.OrderListActivity;
import com.a3dweijing.wetouch2.Activity.PICActivity;
import com.a3dweijing.wetouch2.Activity.SettingActivity;
import com.a3dweijing.wetouch2.Activity.ShoppingCartActivity;
import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.Util.AlerDialogHelp;
import com.a3dweijing.wetouch2.Util.EvenBusUtil;
import com.a3dweijing.wetouch2.Util.FileUtil;
import com.a3dweijing.wetouch2.Util.GlideUtil;
import com.a3dweijing.wetouch2.Util.PermissionapplicationHelp;
import com.a3dweijing.wetouch2.Util.ProgressDialogHelp;
import com.a3dweijing.wetouch2.Util.Util;
import com.a3dweijing.wetouch2.bean.EvenMsg;
import com.a3dweijing.wetouch2.bean.Headmsg;
import com.a3dweijing.wetouch2.bean.ResultMsg;
import com.a3dweijing.wetouch2.bean.User;
import com.a3dweijing.wetouch2.constant.Api;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.a3dweijing.wetouch2.wxapi.WXCallback;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jph.takephoto.app.TakePhotoFragment;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TException;
import com.jph.takephoto.model.TResult;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/3/20. 我的
 */

public class UserFragment extends TakePhotoFragment implements View.OnClickListener
{
    @BindView(R.id.back)
    ImageView back;
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.hard)
    ImageView hard;
    
    @BindView(R.id.user_name)
    TextView userName;
    
    @BindView(R.id.jiangang)
    TextView jiangang;
    
    @BindView(R.id.tv)
    TextView tv;
    
    Unbinder unbinder;
    

    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.my_wallet)
    TextView myWallet;
    
    @BindView(R.id.bay_vip)
    TextView bayVip;
    
    private View view;
    
    private User user;
    
    private ProgressDialog dialog;
    
    private Gson gson;
    

    // 记录是否当前页面在支付
    private boolean isBuyIng = false;
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState)
    {
        if (view != null)
            return view;
        view = LayoutInflater.from(getContext()).inflate(R.layout.user_fragment, container, false);
        EvenBusUtil.register(this);
        unbinder = ButterKnife.bind(this, view);
        initView();
        setOnClick();
        return view;
    }
    
    private void setOnClick()
    {
        topRight.setOnClickListener(this);
        userName.setOnClickListener(this);
        topRight.setOnClickListener(this);
        myWallet.setOnClickListener(this);
        bayVip.setOnClickListener(this);
    }
    
    private static String[] PERMISSIONS_STORAGE =
        {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
    
    private void photpicker()
    {
        PhotoPicker.builder().setPhotoCount(1).setShowCamera(true).setShowGif(true).setPreviewEnabled(true).start(
            getActivity(),
            PhotoPicker.REQUEST_CODE);
    }
    
    private void initView()
    {

        back.setVisibility(View.GONE);
        dialog = ProgressDialogHelp.create(getActivity(), "提示", "正在提交中", false);

        topText.setText("个人中心");
        topRight.setText("设置");
        int[] ids = new int[] {R.id.all_order, R.id.pending_out, R.id.pending_in, R.id.pending_evaluate,
            R.id.health_inquiries, R.id.private_consultant};
        String[] strings = new String[] {"全部订单", "待发货", "待收货", "待评价", "健康报表查询", "我的私人顾问",};
        int[] imgs = new int[] {R.drawable.all_order, R.drawable.pending_out, R.drawable.pending_in,
            R.drawable.pending_evaluate, R.drawable.health_inquiries, R.drawable.private_consultant};
        for (int i = 0; i < ids.length; i++)
        {
            View viewById = view.findViewById(ids[i]);
            viewById.setOnClickListener(this);
            ImageView viewById1 = viewById.findViewById(R.id.imageview);
            viewById1.setImageDrawable(getResources().getDrawable(imgs[i]));
            TextView viewById2 = viewById.findViewById(R.id.tv);
            viewById2.setText(strings[i]);
        }
        int[] idss = new int[] {R.id.stay_pay, R.id.my_privte, R.id.footprint};
        String[] stringss = new String[] {"待付款", "我的收藏", "购物车"};
        for (int i = 0; i < stringss.length; i++)
        {
            View viewById = view.findViewById(idss[i]);
            viewById.setOnClickListener(this);
            TextView viewById2 = viewById.findViewById(R.id.tv2);
            viewById2.setText(stringss[i]);
        }
        user = Singleton.getInstance().getUser();
        String url = GlideUtil.getInstance().checkUrl(user.getUser_head());
        GlideUtil.getInstance().showByCircle(getActivity(), url, hard);
        userName.setText(user.getUser_name() == null ? "暂未设置姓名" : user.getUser_name());
        hard.setOnClickListener(this);
    }
    
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        dialog.cancel();
    }
    
    @Override
    public void onClick(View view)
    {
        if (!Util.isFastClick())
        {
            return;
        }
        switch (view.getId())
        {
            case R.id.hard:
                selectPicture();
                break;
            case R.id.health_inquiries:
                jumpToReadHealthInquiries();
                break;
            
            case R.id.footprint:
                Intent intent1 = new Intent(getActivity(), ShoppingCartActivity.class);
                startActivity(intent1);
                break;
            case R.id.all_order:
                OrderListActivity.startActivity(getActivity(), 0);
                break;
            case R.id.pending_out:
                OrderListActivity.startActivity(getActivity(), 2);
                break;
            case R.id.pending_in:
                OrderListActivity.startActivity(getActivity(), 3);
                break;
            case R.id.stay_pay:
                OrderListActivity.startActivity(getActivity(), 1);
                break;
            case R.id.pending_evaluate:
                Intent intent2 = new Intent(getActivity(), EvaluatedListActivity.class);
                startActivity(intent2);
                break;
            case R.id.my_privte:
                Intent intent_privite = new Intent(getActivity(), MyPriviteActivity.class);
                startActivity(intent_privite);
                break;
            case R.id.top_right:
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.private_consultant:
                Intent intent_cons = new Intent(getActivity(), PICActivity.class);
                intent_cons.putExtra("text", "我的私人顾问");
                startActivity(intent_cons);
                break;
            

            case R.id.bay_vip:
                BuyVipActivity.startActivity(this);
                break;
            case R.id.my_wallet:
                Intent myWallet = new Intent(getActivity(), MyWalletActivity.class);
                startActivity(myWallet);
                
        }
    }
    
    private void selectPicture()
    {
        int permissionapplication = PermissionapplicationHelp
            .Permissionapplication(getActivity(), "android.permission.WRITE_EXTERNAL_STORAGE", PERMISSIONS_STORAGE);
        if (permissionapplication == PERMISSION_GRANTED)
        {
            photpicker();
        }
        else
        {
            Toast.makeText(getActivity(), "无使用权限,请同意该权限", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE)
        {
            if (data != null)
            {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                CropOptions cropOptions =
                    new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();
                try
                {
                    Uri parse = FileUtil.getUri();
                    getTakePhoto().onCrop(Uri.fromFile(new File(photos.get(0))), parse, cropOptions);
                }
                catch (TException e)
                {
                    e.printStackTrace();
                }
            }
        }
        else if (requestCode == BUYVIPACTIVITYCODE && resultCode == RESULT_OK)
        {
            buyVip();
        }
    }
    
    private void buyVip()
    {
        dialog.show();
        String localIpAddress = Util.getLocalIpAddress(getActivity());
        if (localIpAddress == null)
        {
            dialog.dismiss();
            Toast.makeText(getActivity(), "当前ip获取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        Call<JsonObject> call = RetrofitUtil.getInstance()
            .getApiOfPhp()
            .buyVip(Singleton.getInstance().getUser().getUser_id(), "0.01", localIpAddress);
        call.enqueue(new WXCallback(getActivity(), BUYVIP, new CallBack()
        {
            @Override
            public void doNext(int what, Object obj)
            {
                dialog.dismiss();
                if (what != 0)
                    Toast.makeText(getActivity(), "数据获取失败，请重新尝试", Toast.LENGTH_SHORT).show();
                else if (what == 0)
                    isBuyIng = true;
            }
        }));
        
    }
    
    @Override
    public void takeFail(TResult result, String msg)
    {
        super.takeFail(result, msg);
    }
    
    @Override
    public void takeSuccess(TResult result)
    {
        super.takeSuccess(result);
        dialog.show();
        Api api = RetrofitUtil.getInstance().getApi();
        // 构建要上传的文件
        File e = new File(CACHE_DIR + shearshead);
        MultipartBody.Part body = RetrofitUtil.getInstance().getBodyByFile("headFile", e);
        String userId = user.getUser_id();
        MultipartBody.Part no1 = RetrofitUtil.getInstance().getBodyByDate("user_id", userId);
        String url = GlideUtil.getInstance().checkUrl(user.getUser_head());
        MultipartBody.Part no2 = RetrofitUtil.getInstance().getBodyByDate("user_head", url);
        Call<JsonObject> call = api.updatehead(body, no1, no2);
        call.enqueue(new Callback<JsonObject>()
        {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response)
            {
                JsonObject s = response.body();
                gson = new Gson();
                Headmsg headmsg = gson.fromJson(s, Headmsg.class);
                if (headmsg.isFlag())
                {
                    String userHead = headmsg.getUserHead();
                    Singleton.getInstance().getUser().setUser_head(userHead);
                    String s1 = GlideUtil.getInstance().checkUrl(userHead);
                    GlideUtil.getInstance().showByCircle(getActivity(), s1, hard);
                }
                Toast.makeText(getActivity(), headmsg.getMsg(), Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
            
            @Override
            public void onFailure(Call<JsonObject> call, Throwable t)
            {
                Toast.makeText(getActivity(), "服务器访问失败", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        
    }
    
    private void jumpToReadHealthInquiries()
    {
        Intent intent = new Intent(getContext(), HealthInquiriesActivity.class);
        startActivity(intent);
    }
    
    @OnClick({R.id.jiangang})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.jiangang:
                Intent intent1 = new Intent(getActivity(), ApplyForExpertsActivitiy.class);
                startActivity(intent1);
                break;
        }
    }
    
    @Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
    public void onDataSynEvent(EvenMsg evenMsg)
    {
        switch (evenMsg.getWhat())
        {
            case WXPAYSUCCESS:
                if (!isBuyIng)
                    return;
                else
                    isBuyIng = false;
                Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
                break;
            case WXPAYFAIL:
                if (!isBuyIng)
                    return;
                else
                    isBuyIng = false;
                Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                break;
            case RESETNICKNAMEACTIVITYRESTNAME:
                userName.setText(Singleton.getInstance().getUser().getUser_name());
                break;
        }
    }
}
